package com.sen.config.security;

import com.sen.dto.RoleDTO;
import com.sen.entity.Account;
import com.sen.entity.Resource;
import com.sen.entity.Role;
import com.sen.service.AccountService;
import com.sen.service.ResourceService;
import com.sen.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;

@Service
public class MyUserDetailService  implements UserDetailsService {

    @Autowired
    private AccountService accountService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountService.getAccountByUsername(username);
        if (ObjectUtils.isEmpty(account)) {
            return null;
        }
        // 根据用户角色id查询对应的角色信息(里面包含该角色拥有的资源)
        RoleDTO role = roleService.getRoleById(account.getRoleId());
        MyUserDetail userDetail = new MyUserDetail();
        userDetail.setUsername(account.getUsername());
        userDetail.setPassword(account.getPassword());
        userDetail.setRole(role);
        return userDetail;
    }
}
